<template>
    <div>
        <el-main>
            <!-- 查询表单 -->
            <el-form :inline="true" :model="brandModle" size="small" label-width="100px" :rules="rules">
                <el-form-item label="厂商名称">
                    <el-select v-model="brandModle.mid" placeholder="请选择">
                        <el-option v-for="item in makerList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="品牌名称">
                    <el-input v-model="brandModle.brandName" placeholder="请输入品牌名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
                    <el-button type="warning" icon="el-icon-refresh" @click="resetForm">重置</el-button>
                    <el-button type="success" icon="el-icon-plus" @click="handlerCreate">新增</el-button>
                    <el-button type="danger" icon="el-icon-delete" @click="deleteBatch">删除选中</el-button>
                    <el-button type="primary" icon="el-icon-delete" @click="exportExcel">导出表格</el-button>
                </el-form-item>
            </el-form>
            <!-- 数据表格 -->
             <el-table :data="tableData" border stripe 
            @selection-change="handleSelectionChange" 
            style="width: 100%;margin-bottom: 20px;">
                <!-- 复选框 -->
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="序号" width="80">
                    <template slot-scope="scope">
                        {{ (start - 1) * size + scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="厂商名称" prop="makerName"></el-table-column>
                <el-table-column label="品牌名称" prop="brandName"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handlerUpdate(scope.row)" icon="el-icon-edit">修改</el-button>
                        <el-button type="danger" size="mini" @click="handlerDelete(scope.row)" icon="el-icon-delete">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-pagination background layout="total,prev,pager,next,jumper" 
                :current-page="start" :page-size="size"
                :total="total" @current-change="search"
                style="text-align: center;">
            </el-pagination>
            <!-- 对话框 -->
            <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
                <el-form :model="saveBrand" ref="form" :rules="rules" label-width="100px">
                    <el-form-item label="厂商名称" prop="mid">
                        <el-select v-model="saveBrand.mid" placeholder="请选择">
                            <el-option v-for="item in makerList" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="品牌名称" prop="brandName">
                        <el-input v-model="saveBrand.brandName" placeholder="请输入品牌名称"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <!-- 新增与修改调用的是同一个对话框，注意区分 -->
                    <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确 定</el-button>
                </div>
            </el-dialog>
        </el-main>
    </div>
</template>

<script>
// 导入品牌模块的API接口
import brandApi from '@/api/auto_brand'
// 导入厂商模块的API接口
import makerApi from '@/api/auto_maker'
import { getToken } from '@/utils/auth';

export default {
    data() {
        return {
            brandModle: {},
            makerList: [],
            tableData: [],
            multipleSelection: [],
            start: 1,
            size: 5,
            total: 0,
            titleMap: {
                create: '新增品牌',
                update: '修改品牌'
            },
            dialogStatus: '',
            dialogFormVisible: false,
            saveBrand: {},
            rules: {
                mid: [
                    { required: true, message: '请选择厂商名称', trigger: 'change' }
                ],
                brandName: [
                    { required: true, message: '请输入品牌名称', trigger: 'blur' }
                ]
            },
        }
    },
    created() {
        // 在页面加载时，调用查询方法，查询所有厂商数据
        this.selectMaker();
        // 在页面加载时，调用查询方法，查询所有品牌数据
        this.search();
    },
    methods: {
        // 查询所有厂商数据
        async selectMaker() {
            const res = await makerApi.selectAll();
            if(res.success){
                this.makerList = res.data;
            }
        },
        async search(start = 1) {
            this.start = start;
            await brandApi.search(this.start, this.size, this.brandModle).then(res => {
                if(res.success){
                    this.tableData = res.data.records;
                    this.total = res.data.total;
                }
            })
        },
        onSubmit(){
            this.search();
        },
        resetForm(){
            this.tableData = [];
            this.brandModle = {};
            this.search();
        },
        handlerCreate(){
            this.dialogStatus = 'create'; 
            this.saveBrand = {};    
            this.dialogFormVisible = true;  
            this.$nextTick(() => {
                this.$refs['form'].clearValidate()
            }); // 清除校验
        },
        // 响应删除选中的按钮的点击事件
        deleteBatch(){
            if(this.multipleSelection.length == 0){
                this.$message({
                    type: 'warning',
                    message: '请选择要删除的数据!'
                });
            }else{
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(()=>{
                    brandApi.delete(this.multipleSelection).then(res => {
                        // 删除成功
                        if (res.success) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.search();
                        }
                    }).catch((error) => {
                        console.log(error);
                    });
                })
            }
        },
        handleSelectionChange(val){
            this.multipleSelection = [];
            val.forEach(element => {
                this.multipleSelection.push(element.id)
            });
        },
        handlerUpdate(row) {
            this.dialogStatus = 'update';
            // 将当前行的数据赋值给 saveMaker 对象，用于后续的表单数据回显
            this.saveBrand = Object.assign({}, row);
            this.dialogFormVisible = true;
            this.$nextTick(() => {
                this.$refs['form'].clearValidate()
            });
        },
        // 响应删除按钮的点击事件
        handlerDelete(row){
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 点击确定按钮，执行删除操作
                brandApi.delete(row.id).then(res => {
                    // 删除成功
                    if (res.success) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.search();
                    }
                }).catch((error) => {
                    console.log(error);
                });
            })
        },
        createData(){
            this.$refs['form'].validate(async valid => {
                if(!valid){
                    return false;
                }else{
                    brandApi.save(this.saveBrand).then(res => {
                        // 保存成功
                        if (res.success) {
                            this.$message({
                                type: 'success',
                                message: '新增成功!'
                            });
                            // 关闭对话框
                            this.dialogFormVisible = false;
                            this.search();
                        }
                    })
                }
            });
        },
        updateData(){
            this.$refs['form'].validate(async valid => {
                if(!valid){
                    return false;
                }else{
                    brandApi.update(this.saveBrand).then(res => {
                        // 修改成功
                        if (res.success) {
                            this.$message({
                                type: 'success',
                                message: '修改成功!'
                            });
                            this.dialogFormVisible = false;
                            this.search();
                        }
                    })
                }
            })
        },
        exportExcel(){
            let url = `${process.env.VUE_APP_BASE_API}rental/autoBrand/exportExcel?token=${getToken()}`
            window.open(url);
        }

    }
}
</script>